<?php

namespace app\common\model\Post;

use think\Model;


// 评论表
class Comment extends Model
{
    // 指定数据表
    protected $name = 'post_comment';

    // 开启自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 写入到表当中哪个字段
    protected $createTime = 'createtime';  

    // 关闭自动写入
    protected $updateTime = false;
    protected $deleteTime = false;

    // 忽略数据表不存在的字段
    protected $field = true;

    // 每次查询的时候，追加一个自定义字段
    protected $append = [
        'createtime_text',
        'like_text',
        'comment_count',
        'parent_text',
    ];

    // 时间戳转换
    public function getCreatetimeTextAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : '';

        if(empty($createtime))
        {
            return '';
        }
        
        return date('Y-m-d H:i', $createtime);
    }

    //点赞统计
    public function getLikeTextAttr($value, $data)
    {
        //获取到点赞字段
        $like = isset($data['like']) ? $data['like'] : '';

        //字符串转换成数组
        $count = explode(',', $like);

        //过滤 去空，去除重复
        $count = array_filter($count);

        $count = array_unique($count);

        // 统计数组总长度
        return count($count);
    }

    // 统计子评论人数
    public function getCommentCountAttr($value,$data)
    {
        //先获取id
        $id=isset($data['id']) ? $data['id'] : 0;
        
        // 查询
        return model('Post.Comment')->where(['pid'=>$id])->count();
    }

    // 获取上一级评论人的昵称
    public function getParentTextAttr($value, $data)
    {
        $pid = isset($data['pid']) ? $data['pid']: 0;

        $parent = model('Post.Comment')->with(['business'])->find($pid);

        $nickname = isset($parent['business']['nickname_text']) ? $parent['business']['nickname_text'] : '';

        return $nickname;
    }
    public function business()
    {
        return  $this->belongsTo('app\common\model\Business\Business', 'busid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function post()
    {
        return  $this->belongsTo('app\common\model\Post\Post', 'postid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
